package vn.gq.cd.widget;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.actionbarsherlock.app.SherlockFragment;

public abstract class BaseFragment extends SherlockFragment {
	
	public static final String PREV_SCR_TAG = "prev_fragment_tag";
	public static final int RESULT_OK = -1;
	public static final int RESULT_CANCELED = 0;
	
	public String TAG = getClass().getSimpleName();
	
	protected View mLayout;
	
	public abstract int getLayoutId();
	
	public abstract int getContainerId();
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mLayout == null) {
			mLayout = inflater.inflate(getLayoutId(), container, false);
			createView(savedInstanceState);
		} else {
			((ViewGroup) mLayout.getParent()).removeView(mLayout);
		}
		return mLayout;
	}
	
	public abstract void createView(Bundle savedInstanceState);

	protected View findViewById(int resId) {
		return mLayout.findViewById(resId);
	}
	
	public void setPrevTag(String tag) {
		Bundle args = getArguments();
		if (args == null) {
			args = new Bundle();
		}
		args.putString(PREV_SCR_TAG, tag);
		setArguments(args);
	}
	
	public String getPrevTag() {
		try {
			return getArguments().getString(PREV_SCR_TAG);
		} catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void startFragment(int containerId, BaseFragment fragment, String tag) {
		startFragment(containerId, fragment, tag, true);
	}
	
	public void startFragment(int containerId, BaseFragment fragment, String tag, boolean backToPrevious) {
		fragment.setPrevTag(getFragmentTag());
		FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
		ft.detach(this);
		ft.add(containerId, fragment, tag);
		// if backToPrevious set true, when press back fragment will back to previous fragment before
//		if (backToPrevious)
//			ft.addToBackStack(getFragmentTag());
		ft.commit();
	}
	
	public String getFragmentTag() {
		return getClass().getSimpleName() + hashCode();
	}
	
	public void onResume() {
		super.onResume();
		if (getActivity() instanceof ITabHost) {
			((ITabHost) getActivity()).setCurrentFragment(this);
		}
	}
	
	public void onBackPressed() {
		if (getPrevTag() != null) {
			Fragment fragment = getActivity().getSupportFragmentManager().findFragmentByTag(getPrevTag());
			if (fragment != null) {
				FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
				ft.remove(this);
				ft.attach(fragment);
				ft.commit();
			} else {
				getActivity().finish();
			}
		} else {
			getActivity().finish();
		}
	}
}
